import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/components/XImage/ImageWidget.dart';
import 'package:orginone/components/EntityWidget/EntitySwitchWidget/model.dart';
import 'package:orginone/components/XText/XText.dart';
import 'package:orginone/dart/extension/ex_string.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/ActivityWidget/ActivityListWidget/ActivityListWidget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/common/format.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/controller/index.dart';
import 'package:orginone/dart/core/chat/activity.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/target/base/belong.dart';
import 'package:orginone/dart/core/target/base/target.dart';
import 'package:orginone/dart/core/target/outTeam/istorage.dart';
import 'package:orginone/dart/core/target/team/company.dart';
import 'package:orginone/dart/core/thing/directory.dart';
import 'package:orginone/dart/core/thing/standard/index.dart';
import 'package:orginone/main.dart';
import 'package:orginone/pages/portal/assets_management/assets_module/asset_select_modal.dart';
import 'package:orginone/pages/portal/workBench/widgets/event_notification.dart';
import 'package:orginone/pages/portal/workBench/widgets/widget_workbench_common.dart';
import 'package:orginone/routers/app_route.dart';
import 'package:orginone/routers/index.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/string_util.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:orginone/dart/core/thing/standard/form.dart' as core;
import '../../../components/XButton/XButton.dart';
import '../../../components/form/form_widget/form_tool.dart';
import '../../../components/form/widgets/form_datas_view.dart';
import 'package:orginone/dart/base/storages/storage.dart';

///工作台页面
class WorkBenchPage extends StatefulWidget {
  // extends BaseGetListPageView<WorkBenchController, WorkBenchState> {
  // late String type;
  // late String label;

  // HomeController homeController = Get.find<HomeController>();
  // WorkController workController = Get.find<WorkController>();
  // MessageChatsController messageChatsController =
  //     Get.find<MessageChatsController>();"workbench", "工作台"

  const WorkBenchPage({
    super.key,
  });

  @override
  State<StatefulWidget> createState() => _WorkBenchPageState();
}

class _WorkBenchPageState extends State<WorkBenchPage> {
  //待办
  RxString todoCount = "0".obs;
  //应用
  List<IApplication> applications = <IApplication>[];
  //常用应用菜单
  bool enabledSlidable = true;
  // RxList<IFileInfo<XEntity>> listApp = <IFileInfo<XEntity>>[].obs;

  // //当前空间数据
  // RxList<ICompany> spaceList = <ICompany>[].obs;
  ICompany? currentSpace;
  // final List _listDatas = [], _listCompDatas = [], _listDeptDatas = [];

  //关系(个)
  String relationNum = "0";
  //没有存储
  bool noStore = false;
  late core.Form form, compForm, deptForm;
  bool formFlag = false, compFormFlag = false, deptFormFlag = false;
  //磁盘信息
  late DiskInfoType diskInfo = DiskInfoType(
    ok: 0,
    files: 0,
    objects: 0,
    collections: 0,
    fileSize: 0,
    dataSize: 0,
    totalSize: 0,
    fsUsedSize: 0,
    fsTotalSize: 0,
    getTime: "",
  );

  @override
  void initState() {
    super.initState();
    // relationCtrl.provider.chatProvider?.subscribe((key, args) {
    //   if (mounted) {
    //     setState(() {});
    //   }
    // });
    // relationCtrl.provider.chatProvider?.activityProvider.subscribe((p0, p1) {
    //   if (mounted) {
    //     // Future.delayed(const Duration(milliseconds: 100), () {
    //     setState(() {});
    //     // });
    //   }
    // });
    // relationCtrl.provider.chatProvider?.activityProvider.subscribe((p0, p1) {
    //   if (mounted) {
    //     setState(() {});
    //   }
    // });
    // relationCtrl.work.subscribe((key, args) {
    //   todoCount.value = "${relationCtrl.work.todos.value.length}";
    //   // if (mounted) {
    //   //   setState(() {
    //   //   });
    //   // }
    // });
  }

  loadDataForm(IBelong comp) async {
    String id = comp.metadata.id;
    String? belongId = comp.metadata.belongId;
    List<String>? relations = comp.relations;
    Map mapVal = await FormTool.getTargetcacheInfo(id, belongId!, relations);
    if (mapVal.length > 0) {
      if (mapVal.containsKey('MszhSetting')) {
        Map mszhSetting = mapVal['MszhSetting'];
        if (mszhSetting.containsKey('personalForm')) {
          Map<String, dynamic> personalFromMap = mszhSetting['personalForm'];
          form = core.Form(XForm.fromJson(personalFromMap), comp.directory);
          List newData = await FormTool.loadFormDatas(form, 0, 0);
          if (newData.isEmpty) {
            formFlag = false;
          } else {
            formFlag = true;
          }
        } else {
          formFlag = false;
        }

        if (mszhSetting.containsKey('departmentForm')) {
          Map<String, dynamic> departmentFormMap = mszhSetting['departmentForm'];
          deptForm = core.Form(XForm.fromJson(departmentFormMap), comp.directory);
          List newDeptData = await FormTool.loadFormDatas(deptForm, 0, 0);
          if (newDeptData.isEmpty) {
            deptFormFlag = false;
          } else {
            deptFormFlag = true;
          }
        } else {
          deptFormFlag = false;
        }

        if (mszhSetting.containsKey('companyForm')) {
          Map<String, dynamic> companyFormMap = mszhSetting['companyForm'];
          compForm = core.Form(XForm.fromJson(companyFormMap), comp.directory);
          List newCompData = await FormTool.loadFormDatas(compForm, 0, 0);
          if (newCompData.isEmpty) {
            compFormFlag = false;
          } else {
            compFormFlag = true;
          }
        } else {
          compFormFlag = false;
        }
      } else {
        formFlag = false;
        deptFormFlag = false;
        compFormFlag = false;
      }
    } else {
      formFlag = false;
      deptFormFlag = false;
      compFormFlag = false;
    }
  }

  loadData(IBelong comp) async {
    // relationCtrl.user?.getDiskInfo().then((value) {
    //   if (value != null) {
    //     diskInfo = value;
    //   } else {
    //     noStore = true;
    //   }
    // });
    DiskInfoType? type = await comp.getDiskInfo();
    if (type != null) {
      diskInfo = type;
      noStore = false;
    } else {
      noStore = true;
    }
    relationNum = comp.chats
        .where(
          (i) => i.isMyChat && i.typeName != TargetType.group.label,
        )
        .length
        .toString();
  }

  IStorage? _getStorageTarget(IBelong? entity) {
    IStorage? target = entity?.activated;
    return target;
  }

  @override
  Widget build(BuildContext context) {
    // RouteData rd = context.watch<RouteData>();
    return CommandWidget<AppRoute>(
        flag: 'switchSpace',
        builder: (context, args) {
          // loadDataForm(RoutePages.routeData.currPageData.entity as IBelong);
          return ListView(children: [
            renderOperate(),
            EventNotificationPage(
                currentCompany: RoutePages.routeData.currPageData.entity),
            if (null != RoutePages.routeData.currPageData.entity &&
                RoutePages.routeData.currPageData.entity is IBelong)
              _renderRecentApp(
                  RoutePages.routeData.currPageData.entity as IBelong),
            if (null != RoutePages.routeData.currPageData.entity &&
                RoutePages.routeData.currPageData.entity is IBelong)
              rendeStore(RoutePages.routeData.currPageData.entity as IBelong),
            // 个人资产台账
            if (null != RoutePages.routeData.currPageData.entity &&
                RoutePages.routeData.currPageData.entity is IBelong)
              Container(
                color: Colors.white10,
                height: 10.h,
              ),
              _personAssetsManage(RoutePages.routeData.currPageData.entity as IBelong),
            // 部门资产台账
            if (null != RoutePages.routeData.currPageData.entity &&
                RoutePages.routeData.currPageData.entity is IBelong)
              Container(
                color: Colors.white10,
                height: 10.h,
              ),
              _deptementAssetsManage(RoutePages.routeData.currPageData.entity as IBelong),
            // 单位资产台账
            if (null != RoutePages.routeData.currPageData.entity &&
                RoutePages.routeData.currPageData.entity is IBelong)
              Container(
                color: Colors.white24,
                height: 10.h,
              ),
              _companyAssetsManage(RoutePages.routeData.currPageData.entity as IBelong),
            Container(
              color: Colors.white10,
              height: 10.h,
            ),
          ]);
        });
    // return Column(
    //   children: [
    //     Container(
    //       color: XColors.white,
    //       child: buildSelectApp(spaceList.value),
    //     ),
    //     Expanded(
    //         child: Container(
    //             color: XColors.bgListBody,
    //             child: ListView(children: [
    //               renderOperate(),
    //               EventNotificationPage(currentCompany: currentSpace),
    //               _renderRecentApp(),
    //               rendeStore(),
    //             ])))
    //   ],
    // );

    // // return Container(
    // //     color: XColors.bgListBody,
    // //     // padding: const EdgeInsets.fromLTRB(8, 4, 8, 0),
    // //     child: ListView(children: [
    // //       const EventNotificationPage(),
    // //       RenderOperate(),
    // //       _renderRecentApp(),
    // //       // _renderGroupActivity(),
    // //       // _renderFieldCircle(),
    // //       // RenderChat(),
    // //       // RenderWork(),
    // //       // RendeStore(),
    // //       // RendeAppInfo()
    // //     ]));
  }

  // buildSelectApp(List<dynamic> list) {
  //   return Container(
  //       padding: const EdgeInsets.all(16),
  //       color: Colors.white,
  //       width: UIConfig.screenWidth,
  //       child: Row(
  //         children: [
  //           Expanded(
  //             child: SingleChildScrollView(
  //                 scrollDirection: Axis.horizontal,
  //                 child: Row(
  //                   mainAxisAlignment: MainAxisAlignment.start,
  //                   children: [
  //                     XImage.entityIcon(currentSpace,
  //                         size: Size(45.w, 45.w), radius: 4),
  //                     Padding(
  //                       padding: const EdgeInsets.only(left: 8),
  //                       child: Text(currentSpace?.name ?? '',
  //                           textAlign: TextAlign.center,
  //                           overflow: TextOverflow.ellipsis,
  //                           style: XFonts.size24Black0W700),
  //                     )
  //                   ],
  //                 )),
  //           ),
  //           const SizedBox(width: 4),
  //           GestureDetector(
  //             onTap: () {
  //               showSearchApplication(navigatorKey.currentState!.context, spaceList.value,
  //                   title: "切换空间", hint: "搜索", onSelected: (selectData) async {
  //                 currentSpace = selectData[0];
  //                 loadApp();
  //                 setState(() {});
  //                 await relationCtrl.user!.updateCurrentSpace(selectData[0].id);
  //               });
  //             },
  //             child: Row(
  //               children: [
  //                 Text('切换空间', style: XFonts.size22Black0),
  //                 const Icon(
  //                   Icons.arrow_forward_ios,
  //                   size: 18,
  //                 )
  //               ],
  //             ),
  //           )
  //         ],
  //       ));
  // }

  // 发送快捷命令
  renderCmdBtnApp(dynamic file) {
    return Container(
      child: GestureDetector(
        onTap: () {
          if (file is IApplication) {
            RoutePages.jumpAppAssetsList(context, iApplication: file);
          }
        },
        child: SizedBox(
          width: 120.w,
          child: Column(
            children: [
              XImage.entityIcon(file, width: 60.w),
              Container(
                // padding: const EdgeInsets.only(top: 16),
                margin: EdgeInsets.only(top: 16.h),
                child: SizedBox(
                    // height: 16,
                    child: Column(
                  children: [
                    Text(
                      file.name,
                      // softWrap: true,
                      maxLines: 1,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: XColors.doorDesGrey,
                        fontSize: 18.sp,
                        fontFamily: 'PingFang SC',
                        // height: 0.16,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      file.directory.target.name,
                      // softWrap: true,
                      maxLines: 1,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: XColors.doorDesGrey,
                        fontSize: 18.sp,
                        fontFamily: 'PingFang SC',
                        // height: 0.16,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    // Text(
                    //   file.directory.target.space.name,
                    //   // softWrap: true,
                    //   maxLines: 1,
                    //   textAlign: TextAlign.center,
                    //   style: TextStyle(
                    //     color: XColors.doorDesGrey,
                    //     fontSize: 18.sp,
                    //     fontFamily: 'PingFang SC',
                    //     // height: 0.16,
                    //     overflow: TextOverflow.ellipsis,
                    //   ),
                    // ),
                  ],
                )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 渲染最近应用
  Widget _renderRecentApp(IBelong comp) {
    return FutureBuilder<List<IApplication>>(
        future: comp.directory.loadAllApplication().then((list) {
          return list
              // .where((p0) =>
              //     p0.directory.target.space?.spaceId == currentSpace?.id)
              .where((p0) => !p0.groupTags.contains("已删除"))
              .toList();
        }),
        builder:
            (BuildContext context, AsyncSnapshot<List<IApplication>> shot) {
          if (shot.hasData && shot.connectionState == ConnectionState.done) {
            return (shot.data?.length ?? 0) == 0
                ? Container()
                : modelWindow("应用",
                    contentWidget: GridView.count(
                        physics: const NeverScrollableScrollPhysics(),
                        padding: const EdgeInsets.all(0),
                        shrinkWrap: true,
                        addAutomaticKeepAlives: false,
                        addRepaintBoundaries: false,
                        addSemanticIndexes: false,
                        crossAxisCount: 4,
                        childAspectRatio: 1.0,
                        children: shot.data
                                ?.sublist(0, min(16, shot.data?.length ?? 0))
                                .map<Widget>((e) => renderCmdBtnApp(e))
                                .toList() ??
                            []), onMoreTap: () {
                    jumpAllApp(shot.data ?? [], comp as ICompany);
                  });
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        });

    // FutureBuilder<List<IFileInfo<XEntity>>>(
    //   builder: (BuildContext context,
    //       AsyncSnapshot<List<IFileInfo<XEntity>>> datas) {
    //     return Container(
    //         padding:
    //             EdgeInsets.only(left: 0, right: 0, top: 0.h, bottom: 30.h),
    //         child: Wrap(
    //           spacing: 8.0,
    //           runSpacing: 18.0,
    //           children: datas.data
    //                   ?.sublist(0, min(8, datas.data!.length))
    //                   .map<Widget>((e) => renderCmdBtn(e))
    //                   .toList() ??
    //               [],
    //         ));
    //   },
    //   future: relationCtrl.loadCommons(),
    // ));
  }

  // 渲染存储数据信息
  Widget rendeStore(IBelong comp) {
    IStorage? xTarget = _getStorageTarget(comp);
    return modelWindow("数据",
        contentWidget: FutureBuilder(
            future: loadData(comp),
            builder: (BuildContext context, AsyncSnapshot<void> shot) {
              if (shot.connectionState == ConnectionState.done) {
                return noStore
                    ? Container(
                        child: const Center(
                          child: Padding(
                            padding: EdgeInsets.all(10),
                            child: Text("暂无访问权限"),
                          ),
                        ),
                      )
                    : Container(
                        padding: EdgeInsets.only(
                            left: 20, right: 12.w, top: 10.h, bottom: 10.h),
                        child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(xTarget?.name ?? '',
                                        style: TextStyle(
                                            fontSize: 24.sp,
                                            color: XColors.black)),
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 8),
                                      child: Text(
                                          '${formatSize(diskInfo.fsUsedSize)}/${formatSize(diskInfo.fsTotalSize)}',
                                          style: TextStyle(
                                              fontSize: 24.sp,
                                              color: XColors.black)),
                                    ),
                                    renderDataWidget('关  系(个)', relationNum,
                                        '${relationCtrl.provider.chatProvider?.chats.length ?? 0}'),
                                    renderDataWidget(
                                        '数据集(个)',
                                        diskInfo.collections.toString(),
                                        formatSize(diskInfo.dataSize)),
                                    renderDataWidget(
                                        '对象数(个)',
                                        StringUtil.numConversation(
                                            diskInfo.objects),
                                        formatSize(diskInfo.totalSize)),
                                    renderDataWidget(
                                        '文件数(个)',
                                        StringUtil.numConversation(
                                            diskInfo.files),
                                        formatSize(diskInfo.fileSize))
                                  ],
                                ),
                              ),
                              Container(
                                  // width: 120,
                                  // height: 120,
                                  margin:
                                      const EdgeInsets.only(left: 10, top: 40),
                                  child: CircularPercentIndicator(
                                    radius: 52.0,
                                    animation: true,
                                    animationDuration: 500,
                                    lineWidth: 25.0,
                                    percent: diskInfo.fsUsedSize /
                                        diskInfo.fsTotalSize,
                                    center: Container(),
                                    circularStrokeCap: CircularStrokeCap.butt,
                                    backgroundColor: XColors.primary,
                                    progressColor: const Color(0xff14C9C9),
                                  ))
                            ]));
              }
              return const Padding(
                padding: EdgeInsets.only(bottom: 10),
                child: CircularProgressIndicator(),
              );
            }),
        moreWidget: XButton.iconCustomText(
          text: '管理',
          iconLeft: false,
          bgcolor: XColors.transparent,
          textColor: XColors.black,
          icon: XImage.localImage(XImage.iconArrawright, width: 8),
          onPressed: () {
            RoutePages.jumpHome(home: HomeEnum.store, parentData: xTarget);
          },
        ));
  }

  // 个人资产台账
  Widget _personAssetsManage(IBelong comp) {
    return FutureBuilder(
        future: loadDataForm(comp),
        builder:
            (BuildContext context, AsyncSnapshot<void> shot) {
          if (shot.connectionState == ConnectionState.done) {
            return formFlag == false
                ? Container()
                : modelWindow(form.metadata.name,
                contentWidget: FormDataView(
                  form: form,
                  xForm: form.metadata,
                  showType: "three",
                  type: 0,
                ), onMoreTap: () {
                  Storage.setBool('formlisttype', true);
                  RoutePages.to(context: context, path: Routers.formDataListPage, data: form);
                });
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        });
  }

  // 单位资产台账
  Widget _companyAssetsManage(IBelong comp) {
    return FutureBuilder(
        future: loadDataForm(comp),
        builder:
            (BuildContext context, AsyncSnapshot<void> shot) {
          if (shot.connectionState == ConnectionState.done) {
            return compFormFlag == false
                ? Container()
                : modelWindow(compForm.metadata.name,
                contentWidget: FormDataView(
                  form: compForm,
                  xForm: compForm.metadata,
                  showType: "three",
                  type: 0,
                ), onMoreTap: () {
                  Storage.setBool('formlisttype', true);
                  RoutePages.to(context: context, path: Routers.formDataListPage, data: compForm);
                });
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        });
  }

  // 部门资产台账
  Widget _deptementAssetsManage(IBelong comp) {
    return FutureBuilder(
        future: loadDataForm(comp),
        builder:
            (BuildContext context, AsyncSnapshot<void> shot) {
          if (shot.connectionState == ConnectionState.done) {
            return deptFormFlag == false
                ? Container()
                : modelWindow(deptForm.metadata.name,
                contentWidget: FormDataView(
                  form: deptForm,
                  xForm: deptForm.metadata,
                  showType: "three",
                  type: 0,
                ), onMoreTap: () {
                  Storage.setBool('formlisttype', true);
                  RoutePages.to(context: context, path: Routers.formDataListPage, data: deptForm);
                });
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        });
  }

  // 加载存储列表
  List<IStorage> loadStorages(ITarget target) {
    TargetType? type = TargetType.getType(target.typeName);
    List<IStorage> storages = [];
    if (type == TargetType.person) {
      storages = relationCtrl.user?.storages ?? [];
    } else if (type == TargetType.company) {
      storages = relationCtrl.user?.findCompany(target.id)?.storages ?? [];
    }

    return storages;
  }

  List<Directory> loadStoragesDirectory(IStorage data) {
    if (data.isActivate == false) {
      return [];
    }
    List<Directory> datas = [];
    XDirectory tmpDir;
    int id = 0;
    if (null != relationCtrl.user) {
      DirectoryGroupType.getType(data.typeName)?.types.forEach((e) {
        tmpDir = XDirectory(
            id: "${data.id}_$id",
            directoryId: "${data.id}_$id",
            isDeleted: false);
        tmpDir.name = e.label;
        tmpDir.typeName = SpaceEnum.directory.label;
        datas.add(FixedDirectory(
          tmpDir,
          relationCtrl.user!,
          standard: (relationCtrl.user!.currentSpace as ICompany).standard,
          parent: data.directory,
        ));
        id++;
      });
    }
    return datas;
  }

  // 渲染群动态
  Widget _renderGroupActivity() {
    GroupActivity? cohortActivity =
        relationCtrl.provider.chatProvider?.activityProvider.cohortActivity;
    return modelWindow("动态",
        contentWidget: null != cohortActivity
            ? ActivityListWidget(
                activity: cohortActivity,
                showCount: 2,
              )
            : Container(), onMoreTap: () {
      RoutePages.jumpPortal(defaultActiveTabs: ["群动态"]);
    });
  }

  // 渲染好友圈
  Widget _renderFieldCircle() {
    GroupActivity? friendsActivity =
        relationCtrl.provider.chatProvider?.activityProvider.friendsActivity;
    return modelWindow("好友圈",
        contentWidget: null != friendsActivity
            ? ActivityListWidget(
                activity: friendsActivity,
                showCount: 2,
              )
            : Container(), onMoreTap: () {
      RoutePages.jumpPortal(defaultActiveTabs: ["好友圈"]);
    });
  }

  // 操作组件
  Widget renderOperate() {
    // 发送快捷命令
    renderCmdBtn(
        String iconName, String title, ShortcutData item, Color btnColor) {
      return GestureDetector(
        onTap: () {
          // relationCtrl.settingMenuController.hideMenu();
          relationCtrl.showAddFeatures(item);
        },
        child: Column(
          children: [
            XImage.localImage(iconName,
                width: 30.w, color: Colors.white, bgColor: btnColor, radius: 5),
            Container(
              padding: const EdgeInsets.only(top: 16),
              // margin: EdgeInsets.only(top: 10.h),
              child: SizedBox(
                height: 16,
                child: Text(
                  title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: XColors.doorDesGrey,
                    fontSize: 18.sp,
                    fontFamily: 'PingFang SC',
                    height: 0.16,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return modelWindow("快捷操作",
        contentWidget: Container(
            padding: EdgeInsets.only(left: 12.w, right: 12.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                renderCmdBtn(XImage.addFriend, '添加好友',
                    relationCtrl.menuItems[0], const Color(0xFFFF9A5C)),
                renderCmdBtn(XImage.createGroup, '创建群组',
                    relationCtrl.menuItems[4], const Color(0xFF228DEF)),
                renderCmdBtn(XImage.joinGroup, '加入群聊',
                    relationCtrl.menuItems[1], const Color(0xFFFFCE39)),
                renderCmdBtn(XImage.establishmentUnit, '新建单位',
                    relationCtrl.menuItems[2], const Color(0xFFFFCE39)),
                renderCmdBtn(XImage.joinUnit, '加入单位', relationCtrl.menuItems[3],
                    const Color(0xFF59D8A5)),
              ],
            )));
  }

  jumpAllApp(List<IApplication> apps, ICompany comp) {
    // showSearchApplication(navigatorKey.currentState!.context, title: "选择应用", hint: "搜索",
    //     onSelected: (application) async {
    //   if (!application[0].groupTags.contains("常用")) {
    //     application[0].groupTags.add("常用");
    //   }
    //   Future.delayed(const Duration(milliseconds: 400), () {
    //     Get.toNamed(Routers.appAssetListPage, arguments: application[0]);
    //   });
    // });
    // final assetLogic = AssetsManagementLogic.getLogic();
    // List<IApplication> list = apps //assetLogic.applications.value
    //     .where((p0) => p0.groupTags.contains(comp.name))
    //     .toList();
    showSearchApplication(navigatorKey.currentState!.context, apps,
        title: "全部应用", hint: "搜索");
  }

  // // 渲染沟通信息
  // Widget RenderChat() {
  //   return modelWindow("沟通",
  //       contentWidget: Container(
  //         padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
  //         child: Row(
  //           mainAxisAlignment: MainAxisAlignment.spaceAround,
  //           children: [
  //             renderDataItem("好友(人)", 'friend', state.friendNum, HomeEnum.chat,
  //                 () {
  //               // int i = messageChatsController.getTabIndex('friend');
  //               // messageChatsController.changeSubmenuIndex(i);
  //               // messageChatsController.state.tabController.index = i;
  //               RoutePages.jumpChat(defaultActiveTabs: ["好友"]);
  //             }),
  //             renderDataItem(
  //                 "同事(个)", 'company_friend', state.colleagueNum, HomeEnum.chat,
  //                 () {
  //               RoutePages.jumpChat(defaultActiveTabs: ["同事"]);
  //               // messageChatsController.setTabIndex('company_friend');
  //             }),
  //             renderDataItem(
  //                 '群聊(个)', 'group', state.groupChatNum, HomeEnum.chat, () {
  //               RoutePages.jumpChat(defaultActiveTabs: ["群组"]);
  //               // int i = messageChatsController.getTabIndex('group');
  //               // messageChatsController.changeSubmenuIndex(i);
  //               // messageChatsController.state.tabController.index = i;
  //             }),
  //             renderDataItem(
  //                 '单位(家)', 'company', state.companyNum, HomeEnum.chat, () {
  //               RoutePages.jumpChat(defaultActiveTabs: ["单位"]);
  //               // int i = messageChatsController.getTabIndex('company');
  //               // messageChatsController.changeSubmenuIndex(i);
  //               // messageChatsController.state.tabController.index = i;
  //             }),
  //           ],
  //         ),
  //       ),
  //       moreWidget: GestureDetector(
  //           onTap: () {
  //             // homeController.jumpTab(HomeEnum.chat);
  //             RoutePages.jumpChat();
  //           },
  //           child: TextArrow(
  //               title:
  //                   '未读消息 · ${relationCtrl.provider.chatProvider?.noReadChatCount ?? 0}')));
  // }

  Widget renderDataItem(String title, String? code, String number,
      HomeEnum? home, Function()? fun,
      [int size = 0, String info = '']) {
    return Container(
        padding: const EdgeInsets.only(bottom: 10),
        child: GestureDetector(
          onTap: () {
            if (home != null) {
              // homeController.jumpTab(home);
            }
            fun!();
          },
          child: Column(
            children: [
              Text(title,
                  style:
                      TextStyle(fontSize: 18.sp, color: XColors.doorDesGrey)),
              Container(
                padding: const EdgeInsets.only(bottom: 5),
                child: Text(ExString.unitConverter(number),
                    style: TextStyle(fontSize: 22.sp)),
              ),
              Text(size >= 0 ? '大小:${formatSize(size)}' : info,
                  style:
                      TextStyle(fontSize: 18.sp, color: XColors.doorDesGrey)),
            ],
          ),
        ));
  }

  // // 渲染办事信息
  // Widget RenderWork() {
  //   return modelWindow("办事",
  //       contentWidget: Container(
  //           padding: EdgeInsets.only(
  //               left: 12.w, right: 12.w, top: 10.h, bottom: 10.h),
  //           child: Row(
  //               mainAxisAlignment: MainAxisAlignment.spaceAround,
  //               children: [
  //                 renderDataItem('待办', 'todo', state.todoCount, HomeEnum.work,
  //                     () {
  //                   // int i = workController.getTabIndex('todo');
  //                   // workController.changeSubmenuIndex(i);
  //                   // workController.state.tabController.index = i;
  //                   RoutePages.jumpWork(defaultActiveTabs: ["待办"]);
  //                 }),
  //                 renderDataItem(
  //                     '已办', 'done', state.completedCount, HomeEnum.work, () {
  //                   // int i = workController.getTabIndex('done');
  //                   // workController.changeSubmenuIndex(i);
  //                   // workController.state.tabController.index = i;
  //                   RoutePages.jumpWork(defaultActiveTabs: ["已办"]);
  //                 }),
  //                 renderDataItem('抄送', 'alt', state.copysCount, HomeEnum.work,
  //                     () {
  //                   // int i = workController.getTabIndex('alt');
  //                   // workController.changeSubmenuIndex(i);
  //                   // workController.state.tabController.index = i;
  //                   RoutePages.jumpWork(defaultActiveTabs: ["抄送"]);
  //                 }),
  //                 renderDataItem(
  //                     '发起的', 'create', state.applyCount, HomeEnum.work, () {
  //                   // int i = workController.getTabIndex('create');
  //                   // workController.changeSubmenuIndex(i);
  //                   // workController.state.tabController.index = i;
  //                   RoutePages.jumpWork(defaultActiveTabs: ["已发起"]);
  //                 }),
  //               ])),
  //       moreWidget: GestureDetector(
  //           onTap: () {
  //             // homeController.jumpTab(HomeEnum.work);
  //             RoutePages.jumpWork();
  //           },
  //           child: const TextArrow(title: '前往审批')));
  // }

  // 渲染应用信息
  Widget RendeAppInfo() {
    return modelWindow("常用应用",
        contentWidget: Container(
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: applications
                    .where((i) => i.cache.tags?.contains("常用") ?? false)
                    .map((element) => loadAppCard(element))
                    .toList())),
        moreWidget: const XText.buttonHollow('全部应用'));
  }

  //渲染应用数据
  Widget loadAppCard(IApplication item) {
    var useAlays = item.cache.tags?.contains('常用');
    return GestureDetector(
      onTap: () {
        // TODO全部应用
      },
      child: Slidable(
        enabled: enabledSlidable,
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          children: [
            SlidableAction(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              icon: Icons.vertical_align_top,
              label: useAlays! ? "取消常用" : "设为常用",
              onPressed: (BuildContext context) async {
                if (useAlays) {
                  item.cache.tags =
                      item.cache.tags?.where((i) => i != '常用').toList();
                  item.cacheUserData();
                } else {
                  item.cache.tags = item.cache.tags ?? [];
                  item.cache.tags?.add('常用');
                  item.cacheUserData();
                }
              },
            ),
          ],
        ),
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15.w),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 7.h),
            decoration: BoxDecoration(
                border: Border(
                    bottom:
                        BorderSide(color: Colors.grey.shade300, width: 0.4))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageWidget(
                  item.metadata.icon,
                  size: 50.w,
                  iconColor: const Color(0xFF9498df),
                ),
                Text(item.name),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class BelongData extends EntitySwitchModel<IBelong> {
  BelongData(super.title);

  @override
  Future<IBelong?> getInitData() {
    IBelong currentSpace = relationCtrl.user!.currentSpace;
    return Future(() => currentSpace);
  }

  @override
  Future<List<ICompany>> getInitDatas() {
    return Future(() => relationCtrl.user?.companys ?? []);
  }

  @override
  void setCurrData(IBelong? currData) {
    if (null != currData) {
      relationCtrl.user?.updateCurrentSpace(currData);
    }
  }
}
